package com.rainbow.support.xss.handler;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * XSS过滤 jackson 反序列化器
 *
 * @author rainbow
 */
@Slf4j
public class JsonDeserializer extends StringDeserializer {

	private final JsonXssCleaner jsonXssCleaner;

	public JsonDeserializer(JsonXssCleaner jsonXssCleaner) {
		this.jsonXssCleaner = jsonXssCleaner;
	}

	@Override
	public String deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
		// json 字段名
		String name = p.getCurrentName();
		// 字符串类型
		if (p.hasToken(JsonToken.VALUE_STRING)) {
			if (StringUtils.isBlank(p.getText())) {
				return null;
			}
			String res=jsonXssCleaner.escape(p.getText());
			return res;
		}
		JsonToken jsonToken = p.getCurrentToken();
		if (jsonToken.isScalarValue()) {
			String text = p.getValueAsString();
			if (StringUtils.isNotBlank(text)) {
				String res= jsonXssCleaner.escape(text);
				return res;
			}
		}
		throw MismatchedInputException.from(p, String.class, "rainbow-xss: can't deserialize json name:" + name + " value of type java.lang.String from " + jsonToken);
	}


}
